<?php

/**
 * @Description    
 * @Author         zhaojiping
 * @Copyright      山东艾思软件科技有限公司(https://www.aisisofit.cn)
 * @Date           2022-6-15
 * @CreateBy       vs code
 */


declare(strict_types=1);

namespace app\base\controller;

use TencentCloud\Common\Credential;
use TencentCloud\Common\Profile\ClientProfile;
use TencentCloud\Common\Profile\HttpProfile;
use TencentCloud\Sts\V20180813\Models\GetFederationTokenRequest;
use TencentCloud\Sts\V20180813\StsClient;

class CosController {
    public function sts() {

        $config = cache('config');
        $bucket = $config["cos_bucket"];   // 存储桶
        $region = $config["cos_region"]; // 地区
        $secretId = $config["cos_secret_id"];  // 密钥ID
        $secretKey = $config["cos_secret_key"]; // 密钥

        $cred = new Credential($secretId, $secretKey);
        $httpProfile = new HttpProfile();
        $httpProfile->setEndpoint("sts.tencentcloudapi.com");

        $clientProfile = new ClientProfile();
        $clientProfile->setHttpProfile($httpProfile);

        // 授权策略
        $policy =  [
            "version" => "2.0",
            "statement" => [
                [
                    "principal" =>  "*",
                    "effect" => "allow",
                    "action" => [
                        "cos:*",
                    ],
                    "resource" => "*",
                ]
            ]
        ];

        $client = new StsClient($cred, $region, $clientProfile);

        $req = new GetFederationTokenRequest();
        $params = [
            "Name" => "web",
            "Policy" => json_encode($policy),
            "DurationSeconds" => 1800
        ];
        $req->fromJsonString(json_encode($params));

        $resp = $client->GetFederationToken($req);

        $res = json_decode($resp->toJsonString(), true);
        $res['StartTime'] = time();
        $res['Bucket'] = $bucket;
        $res['Region'] = $region;

        return json(['status' => 1, 'info' => '', 'data' => $res]); // abc
    }
}
